package org.jeecg.modules.yslb.controller;

import java.io.*;
import java.sql.Blob;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.Doc2Pdf;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
//import org.jeecg.modules.fleetuser.entity.FleetUser;
//import org.jeecg.modules.fleetuser.service.FleetUserService;
//import org.jeecg.modules.fleetuser.vo.FleetUserVo;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.yslb.entity.FleetUsers;
import org.jeecg.modules.yslb.service.FleetUsersService;
import org.jeecg.modules.yslb.vo.FleetUsersUrl;
import org.jeecg.modules.yslb.vo.FleetUsersVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

/**
 * @Description: 信息管理
 * @Author: auth
 * @Date: 2020-05-28
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "信息管理")
@RestController
@RequestMapping("/fleetUser")
public class FleetUsersController {
	@Autowired
	private FleetUsersService fleetUsersService;
	@Value("${jeecg.path.upload}")
	private String uploadpath;


	/**
	 * 分页列表查询
	 *
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "信息管理-分页列表查询")
	@ApiOperation(value = "信息管理-分页列表查询", notes = "信息管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<FleetUsers>> queryPageList(FleetUsers fleetUser,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req,
			HttpServletResponse res) {
		Result<IPage<FleetUsers>> result = new Result<IPage<FleetUsers>>();
		QueryWrapper<FleetUsers> queryWrapper = QueryGenerator.initQueryWrapper(fleetUser, req.getParameterMap());
		Page<FleetUsers> page = new Page<FleetUsers>(pageNo, pageSize);
		IPage<FleetUsers> pageList = fleetUsersService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}


	/**
	 * 通过id查询
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "信息-通过id查询")
	@ApiOperation(value = "信息-通过id查询", notes = "信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<FleetUsersUrl> queryById(@RequestParam(name = "nrid", required = true)String nrid, String id, HttpServletRequest req,
			HttpServletResponse res) {
		Result<FleetUsersUrl> result = new Result<FleetUsersUrl>();
		FleetUsersVo fleetUsersVo = fleetUsersService.selectPartners(nrid);
//		FleetUsers fleetUsers=fleetUsersService.getById(id);
		FleetUsersUrl userurl=new FleetUsersUrl();
		String filepath = id;
        try {
            InputStream in = new ByteArrayInputStream(fleetUsersVo.getContent()); // 建立输出流
            FileOutputStream file = new FileOutputStream(filepath);
            //int len = (int) ((Blob)fleetUsersVo.getCONTENT()).length();
			int len =fleetUsersVo.getContent().length;
			byte[] buffer = new byte[len]; // 建立缓冲区
            while ((len = in.read(buffer)) != -1) {
                file.write(buffer, 0, len);
            }
            file.close();
            in.close();
        } catch (Exception e) {
        }

		if(filepath.compareTo(".doc")>0){
			HashMap<String,String> pdfMap= Doc2Pdf.doc2Pdf(filepath,uploadpath+File.separator);
			filepath = pdfMap.get("fileName");
			System.out.println(pdfMap.get("filePath"));
		};


        userurl.setUrl(filepath);
		result.setResult(userurl);
		return result;
	}
	/**
	 * 通过id查询
	 *
	 * @return
	 */
	@AutoLog(value = "信息-通过id查询")
	@ApiOperation(value = "信息-通过id查询", notes = "信息-通过id查询")
	@GetMapping(value = "/perview")
	public void queryFileById(@RequestParam(name = "nrid", required = true) String nrid,
											   @RequestParam(name="id",required = true) String fileName,
										   		HttpServletResponse response) {
		Result<HashMap<String,String>> result = new Result<>();
		Map<String,String > map = new HashMap<>();
		String pdfFilePath = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
			response.setContentType("application/octet-stream");
			FleetUsersVo fleetUsersVo = fleetUsersService.selectPartners(nrid);
			InputStream in = new ByteArrayInputStream(fleetUsersVo.getContent()); // 建立输出流
			FileOutputStream file = new FileOutputStream(fileName);
			//int len = (int) ((Blob)fleetUsersVo.getCONTENT()).length();
			int len =fleetUsersVo.getContent().length;
			byte[] buffer = new byte[len]; // 建立缓冲区
			while ((len = in.read(buffer)) != -1) {
				file.write(buffer, 0, len);
			}
			file.close();
			in.close();
			if(!fileName.contains(".pdf")){
				HashMap<String,String> pdfMap= Doc2Pdf.doc2Pdf(fileName,uploadpath+File.separator);
				pdfFilePath = pdfMap.get("filePath");
			}else{
				pdfFilePath =fileName;
			}
			File pdfFile = new File(pdfFilePath);
			byte [] data = null;
			inputStream = null;
			inputStream = new FileInputStream(pdfFile);
			data=new byte[inputStream.available()];
			inputStream.read(data);
			response.getOutputStream().write(data);
			inputStream.close();
			response.setHeader("Access-Control-Allow-Origin", "*");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@GetMapping(value = "/download")
	public void view(@RequestParam(name = "nrid", required = true)String nrid,
					 @RequestParam(name = "id", required = true)String fileName,
					 @RequestParam(name = "bt", required = true)String bt,
					 HttpServletResponse response) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			FleetUsersVo fleetUsersVo = fleetUsersService.selectPartners(nrid);
			InputStream in = new ByteArrayInputStream(fleetUsersVo.getContent()); // 建立输出流
			String fileName_new= bt+fileName.substring(fileName.lastIndexOf("."));
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName_new.getBytes("UTF-8"),"iso-8859-1"));
			inputStream  = new ByteArrayInputStream(fleetUsersVo.getContent());
			outputStream = response.getOutputStream();
			byte[] buf = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				outputStream.write(buf, 0, len);
			}
			response.flushBuffer();
		} catch (IOException e) {
			log.error("预览文件失败" + e.getMessage());
			response.setStatus(404);
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}

	}

	private static String PDFToBase64(File file) {
		BASE64Encoder encoder = new BASE64Encoder();
		FileInputStream fin =null;
		BufferedInputStream bin =null;
		ByteArrayOutputStream baos = null;
		BufferedOutputStream bout =null;
		try {
			fin = new FileInputStream(file);
			bin = new BufferedInputStream(fin);
			baos = new ByteArrayOutputStream();
			bout = new BufferedOutputStream(baos);
			byte[] buffer = new byte[1024];
			int len = bin.read(buffer);
			while(len != -1){
				bout.write(buffer, 0, len);
				len = bin.read(buffer);
			}
			//刷新此输出流并强制写出所有缓冲的输出字节
			bout.flush();
			byte[] bytes = baos.toByteArray();
			return encoder.encodeBuffer(bytes).trim();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				fin.close();
				bin.close();
				bout.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void main(String[] args) {
		String tt = "sdfsdfsdfsdf.dov";
		System.out.println(tt.lastIndexOf("."));
		System.out.println(tt.substring(tt.lastIndexOf(".")));
	}

}
